package com.mp.approvalreq.dao.impl;

import com.mp.approvalreq.dao.CommentDao;
import com.mp.approvalreq.entity.Comment;
import com.mp.approvalreq.entity.MessageRead;
import com.plusmoney.util.DateTimeHelper;
import com.plusmoney.util.SQLLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CommentDaoImpl extends AbstractDao implements CommentDao {

    private static final Logger logger = LoggerFactory.getLogger(CommentDaoImpl.class);

    private Connection connection;

    public CommentDaoImpl(Connection connection) {
        this.connection = connection;
    }

    private PreparedStatement getPreparedStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    /**
     * @param condition 条件（where……[order by……]/[group by ……] [limit……]）
     * @return
     */
    @Override
    String getQuerySql(String condition) {
        final String query = "select Fid, Fcompany_id, Frequest_id, Fcrt_by, Fcrt_by_ciid,"
                + " Fmessage_type, Fmessage, Fimage, Fcrt_at, Fis_read,"
                + " Fis_cancel, Fis_refuse, Ffile_name"
                + " from request_comment";
        return String.format("%s %s", query, condition);
    }

    @Override
    Comment getObject(ResultSet rs) throws SQLException {
        Comment comment = new Comment();
        comment.setId(rs.getInt(1));
        comment.setCompanyId(rs.getInt(2));
        comment.setRequestId(rs.getInt(3));
        comment.setCreateId(rs.getInt(4));
        comment.setCreateCompanyInfoId(rs.getInt(5));

        comment.setType(rs.getInt(6));
        comment.setMsg(rs.getString(7));
        comment.setFileCode(rs.getString(8));
        comment.setCrtTime(getTimeStr(rs.getTimestamp(9), DateTimeHelper.YEAR_MONTH_DAY_HOUR_MINUTE_PATTERN));
        comment.setIsRead(rs.getInt(10));

        comment.setIsCancel(rs.getInt(11));
        comment.setIsRefuse(rs.getInt(12));
        comment.setFileName(rs.getString(13));

        return comment;
    }

    @Override
    public List<Comment> selectCommentList(Integer requestId) throws SQLException {
        List<Comment> list = new ArrayList<>();
        String sql = getQuerySql("where Frequest_id = ? order by Fid desc");

        try (PreparedStatement ps = getPreparedStatement(sql)) {
            ps.setInt(1, requestId);
            logger.info(SQLLogger.logSQL(sql, requestId));

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    list.add(getObject(rs));
                }
            }
        }
        return list;
    }

    @Override
    public int insertComment(Comment comment) throws SQLException {
        String sql = " insert into request_comment set"
                + " Fcompany_id = ?, Frequest_id = ?, Fcrt_by = ?, Fcrt_by_ciid = ?, Fmessage_type = ?,"
                + " Fmessage = ?, Fimage = ?, Ffile_name = ?, Fis_refuse = ?, Fcrt_at = now()";

        try (PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
            ps.setInt(1, comment.getCompanyId());
            ps.setInt(2, comment.getRequestId());
            ps.setInt(3, comment.getCreateId());
            ps.setInt(4, comment.getCreateCompanyInfoId());
            ps.setInt(5, comment.getType());

            ps.setString(6, comment.getMsg());
            ps.setString(7, comment.getFileCode());
            ps.setString(8, comment.getFileName());
            ps.setInt(9, comment.getIsRefuse());
            logger.info(SQLLogger.logSQL(sql, comment.getCompanyId(), comment.getRequestId(), comment.getCreateId(),comment.getCreateCompanyInfoId(), comment.getType(),
                    comment.getMsg(), comment.getFileCode(), comment.getFileName(), comment.getIsRefuse()));

            ps.executeUpdate();

            try (ResultSet rs = ps.getGeneratedKeys()) {
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }
        }
        return 0;
    }


    @Override
    public Comment selectCommentById(Integer id) throws SQLException {
        String sql = getQuerySql("where Fid = ?");

        try (PreparedStatement ps = getPreparedStatement(sql)) {
            ps.setInt(1, id);
            logger.info(SQLLogger.logSQL(sql, id));

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    return getObject(rs);
                }
            }
        }
        return null;
    }

    @Override
    public Comment selectLastComment(Integer requestId) throws SQLException {
        String sql = getQuerySql("where Frequest_id= ? and Fis_cancel = 0 order by Fcrt_at desc limit 1");

        try (PreparedStatement ps = getPreparedStatement(sql)) {
            ps.setInt(1, requestId);
            logger.info(SQLLogger.logSQL(sql, requestId));

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    return getObject(rs);
                }
            }
        }
        return null;
    }

    @Override
    public void UpdateCommentCancelStatus(Integer id) throws SQLException {
        String sql = " update request_comment set Fis_cancel = 1 where Fid = ? limit 1 ";

        logger.info("撤回评论:" + SQLLogger.logSQL(sql, id));

        try (PreparedStatement ps = getPreparedStatement(sql)) {
            ps.setInt(1, id);
            ps.executeUpdate();
        }
    }

}
